<template>
    <div class="mmv-map-page custom_card">
        <div class="mmv-side-bar" v-loading="timerLoading">
            <div>
                <el-input v-model="queryForm.carNo" placeholder="请输入地址" style="width:100%"></el-input>
                <div style="display: flex; margin: 10px 0">
                    <el-input v-model="queryForm.carNo" placeholder="请输入车牌号" style="margin-right: 10px"></el-input>
                    <el-button type="primary" @click="mmvRef">查询</el-button>
                    <el-button @click="handleReset">重置</el-button>
                </div>
            </div>
            <div class="mmv-car-wrap">
                <template v-for="item in carBasicMonitoring">
                    <div class="mmv-car-item" :class="{ active: item.carId == nowCar.carId }" :key="item.carId"
                        @click="onClickCar(item)">
                        <!--                        <i class="el-icon-truck"></i>-->
                        <div class="car-item-row">
                            <span>{{ item.carNo }}</span>
                            <span style="color: red;font-size: 14px;">{{ item.alarmName }}</span>
                            <span style="color: green;font-size: 14px;">
                                {{ 1 === item.deviceSubStatus ? '行驶' : 2 === item.deviceSubStatus ? '静止' : 3 ===
                                    item.deviceSubStatus ?
                                    '离线' : '' }}</span>
                        </div>
                        <div class="car-item-row">
                            <el-popover placement="right" width="300" trigger="click" v-model="item.deviceVisible">
                                <el-table :data="devicesList">
                                    <el-table-column width="150" property="deviceNo" label="设备编号"></el-table-column>
                                    <el-table-column label="操作" align="center" class-name="small-padding fixed-width"
                                        width="100">
                                        <template v-slot="{ row }">
                                            <span style="color: green;" v-if="item.deviceNo === row.deviceNo">当前</span>
                                            <el-button v-else size="small"
                                                @click="changeToggleCarBindInformation(row.deviceNo, item)">切换</el-button>
                                        </template>
                                    </el-table-column>
                                </el-table>
                                <el-button type="text" slot="reference" @click.stop="getDevice(item)">{{ item.deviceNo
                                    }}<i class="el-icon-arrow-right el-icon--right"></i></el-button>
                            </el-popover>

                            <span style="color: #999;font-size: 14px;margin-top: 10px">{{
                                1 === item.deviceKind ? '有线' : 2 === item.deviceKind ? '无线' : '' }}</span>
                        </div>


                        <!--                        <i class="el-icon-location-information"></i>-->
                    </div>
                </template>
            </div>
        </div>
        <MmvMap :carBasicMonitoring="carBasicMonitoring" ref="MmvMap" @markerClick="markClick">
        </MmvMap>
        <!--v-loading="timerLoading"-->
        <el-dialog :visible.sync="showInfoWindow" width="950px" :destroy-on-close="true">
            <CarinfoDialog ref="carInfoDialog" :now-car="nowCar" @handleTrace="handleTrace" @handleOrder="handleOrder"
                @handleTrackAnimation="handleTrackAnimation"></CarinfoDialog>
        </el-dialog>

        <el-dialog title="查看轨迹" :visible.sync="showTrackAnimation" width="1100px" append-to-body
            :destroy-on-close="true">
            <!-- <iframe :src="'./map-track.html?trackPath='+JSON.stringify(trackPath)" style="width:100%;height:580px" frameborder="0"></iframe> -->
            <MmvMapTrack :path="trackPath"></MmvMapTrack>
        </el-dialog>

        <el-dialog title="下发指令" :visible.sync="showzhilin" width="700px" append-to-body :destroy-on-close="true"
            @close="sendinstructions = ''">

            <el-descriptions title="" :column="2">
                <!--        <el-descriptions-item label-class-name="my-descriptions-label" label="设备名称">{{
                    nowCar.carNo || '&#45;&#45;'
                  }}
                  </el-descriptions-item>-->
                <!-- <el-descriptions-item label-class-name="my-descriptions-label" label="设备IMEI">{{
            nowCar.deviceNo || '--'
          }}
          </el-descriptions-item> -->
                <el-descriptions-item label-class-name="my-descriptions-label" label="设备IMEI">{{

                    currentDeviceNo || '--'
                }}
                </el-descriptions-item>
                <el-descriptions-item label-class-name="my-descriptions-label" label="车牌号">{{
                    nowCar.carNo || '--'
                    }}
                </el-descriptions-item>
                <el-descriptions-item label-class-name="my-descriptions-label" label="车架号">{{
                    nowCar.vinNo || '--'
                    }}
                </el-descriptions-item>
            </el-descriptions>

            <el-divider></el-divider>

            <el-radio-group v-model="radio" size="middle">
                <el-radio v-for="(item, index) in deviceOrderList" :key="item.id" :label="item.ordername"
                    :value="item.id">

                </el-radio>
                <!--        <span style="font-size: 12px;">({{ item.orderExplain }})</span>-->

            </el-radio-group>
        </el-dialog>
    </div>
</template>

<script>
import * as MmvApi from '@/api/mmv'
import MmvMap from './components/gpsMap.vue'
import MmvMapTrack from './components/map-track.vue'
import data from './components/data.json'
import { v4 } from 'uuid'
import uilts from "@/utils";
import { getImeiGPSCmd, reportingAddress } from "@/api/mmv";
import CarinfoDialog from "@/views/car/vehiclemonitoringpage/components/carinfo-dialog";
import * as carApi from '@/api/car/car_basic';
import json from 'highlight.js/lib/languages/json'
export default {
    name: 'BaiduMapDemo',
    components: {
        MmvMap,
        MmvMapTrack,
        CarinfoDialog,
    },
    dicts: ['car_status', 'car_repair_status', 'sys_order_source', 'sys_order_status', 'gps_alarm_type'],
    data() {
        return {
            radio: '',
            showzhilin: false,
            mileage: '',
            showTrackAnimation: false,
            carBasicMonitoringCount: {
                allCar: 0,
                drivingCar: 0,
                staticCar: 0,
                offlineCar: 0,
                alarmCar: 0,
            },
            carBasicMonitoring: [],
            queryForm: {
                carNo: '',
                deviceSubStatus: '0',
                pageNum: 1,
                pageSize: 100,
                deviceNo: '',
                time: new Date(),
            },
            nowCar: {},
            trackPath: [],
            timer: null,
            timerNum: 30,
            timerLoading: false,
            startTime: null,
            endTime: null,
            highRecortAddress: '',
            showInfoWindow: false,
            deviceOrderList: [],
            firstEnter: false,
            devicesList: [],
            currentDeviceNo: '', //下发指令当前涉笔
        }
    },
    mounted() {
        if (this.$route.query.id) {
            this.firstEnter = true
        }
        this.getcarBasicMonitoringCount()
        this.getcarBasicMonitoring()
        this.getImeiGPSCmd()
    },
    destroyed() {
        clearInterval(this.timer)
    },
    methods: {
        changeToggleCarBindInformation(deviceNo, item) {
            carApi.toggleCarBindInformation({
                carId: item.carId,
                deviceNo: deviceNo
            }).then(res => {
                item.deviceVisible = false;
                this.mmvRef();
                this.$message.success(res.msg)
            })
        },
        getDevice(item) {
            carApi.carBindInformationList(item.carId).then(res => {
                this.devicesList = res.data;
                this.carBasicMonitoring.map(car => {
                    if (item.deviceNo !== car.deviceNo) {
                        car.deviceVisible = false;
                    }
                })
            })
        },
        submitForm() {
            MmvApi.sendinstructions({
                deviceId: this.nowCar.deviceNo,
                mileage: this.mileage,
            }).then((res) => {
                this.$message.success(res.msg)
            })
        },
        getImeiGPSCmd() {
            MmvApi.getImeiGPSCmd({
                deviceNo: this.nowCar.deviceNo
            }).then(res => {
                this.deviceOrderList = res.data
            })
        },
        mmvRef() {
            this.timerLoading = true
            this.getcarBasicMonitoringCount().then((response) => {
                return this.getcarBasicMonitoring()
            }).finally(() => {
                this.timerLoading = false
            })


        },

        repositioning() {
            if (this.timerNum < 25) {
                this.timerNum = 30
                clearInterval(this.timer)
                // this.timerLoading = true
                return MmvApi.wodafuCarCurrentLocation()
                    .then((response) => {
                        return this.getcarBasicMonitoringCount()
                    })
                    .then((response) => {
                        return this.getcarBasicMonitoring()
                    })
                    .then((response) => {
                        //this.timerLoading = false
                        this.timerNum = 30
                    }).finally(() => {
                        //  this.timerLoading = false
                    })
            } else {
                this.$message.warning('请勿频繁刷新!')
            }

        },
        getcarBasicMonitoringCount() {
            return MmvApi.carBasicMonitoringCount().then((response) => {
                this.carBasicMonitoringCount = response.data
            })
        },
        getcarBasicMonitoring() {
            return MmvApi.carBasicMonitoring(this.queryForm).then((response) => {
                this.carBasicMonitoring = response.rows
                //自定义多设备切换设备显示字段
                this.carBasicMonitoring = this.carBasicMonitoring.map(item => {
                    this.$set(item, 'deviceVisible', false);
                    return item;
                })

                if (this.firstEnter) {
                    this.carBasicMonitoring.forEach(item => {
                        if (item.carId === this.$route.query.id) {
                            this.onClickCar(item)
                        }
                    })
                    this.firstEnter = false
                }
                console.log('车辆>>>', this.carBasicMonitoring);
            })
        },
        handleClick() {
            // this.getcarBasicMonitoring();
            this.mmvRef()
        },
        onClickCar(item) {
            this.nowCar = item
            // this.showInfoWindow = true
            // this.$nextTick(()=>{
            //   this.$refs.carInfoDialog.getBindDeviceList();
            // })
            const point = {
                lng: this.nowCar.lng || 0,
                lat: this.nowCar.lat || 0
            }
            this.$refs.MmvMap.makerCurrentCar(point, this.nowCar);

        },
        markClick() {
            this.showInfoWindow = true
            this.$nextTick(() => {
                this.$refs.carInfoDialog.getBindDeviceList();
            })
        },

        handleReset() {
            this.nowCar = {}
            this.$refs.MmvMap.handleReset()
            this.mmvRef()
            this.queryForm.carNo = ''
            this.queryForm.time = new Date()
        },
        // 查看轨迹
        handleTrackAnimation(deviceItem) {
            this.timerLoading = true
            const uilts = require('@/utils/index')
            // const deviceNo = this.queryForm.deviceNo || this.nowCar.deviceNo
            const deviceNo = deviceItem.deviceNo || this.nowCar.deviceNo
            this.startTime = uilts.parseTime(
                new Date(this.queryForm.time).getTime() - 24 * 60 * 60 * 1000);
            this.endTime = uilts.parseTime(new Date(this.queryForm.time))
            this.endTime = uilts.parseTime(new Date(this.queryForm.time))

            //新加
            const manufacturer = deviceItem.manufacturer || this.nowCar.manufacturer;
            const simCard = deviceItem.simCard || this.nowCar.simCard;
            MmvApi.getTrack({
                deviceNo: deviceNo,
                trackStartTime: this.startTime,
                trackEndTime: this.endTime,
                // manufacturer: this.nowCar.manufacturer
                manufacturer: manufacturer
            }).then((response) => {
                this.timerLoading = false
                this.trackPath = response.data.trackPlayList || []
                this.jump(deviceNo, manufacturer, response.data.totalMileage, this.nowCar.carNo, simCard, deviceItem)
            })
                .catch((err) => {
                    this.timerLoading = false
                    // this.trackPath = data
                    // setTimeout(() => {
                    // this.$message.error('请求服务器错误，现在播放一段示例轨迹')
                    // }, 1500)
                    // this.jump()
                    this.$message.error('暂无轨迹')
                })
        },
        // 实时跟踪
        handleTrace(deviceItem) {
            let routeUrl = this.$router.resolve({
                path: '/map-trace',
                // query: { nowCarNo: this.nowCar.carNo },
                query: { deviceItem: JSON.stringify(deviceItem) },
            })
            window.open(routeUrl.href, '_blank')
        },
        // 下发指令
        handleOrder(deviceItem) {
            this.showzhilin = true
            this.currentDeviceNo = deviceItem.deviceNo;
        },
        jump(deviceNo, manufacturer, totalMileage, carNo, simNo, deviceItem) {
            const id = v4()
            let routeUrl = this.$router.resolve({
                path: '/map-track',
                query: { id: id, aaa: this.startTime, bbb: this.endTime, deviceNo, manufacturer, totalMileage, carNo, simNo, deviceItem: JSON.stringify(deviceItem) },
            })

            sessionStorage.setItem(id, JSON.stringify(this.trackPath))
            window.open(routeUrl.href, '_blank')
        },
    },
}
</script>

<style lang="scss" scoped>
.mmv-map-page {
    display: flex;
    margin: 12px 17px;
    height: calc(100vh - 140px);
}

.mmv-item {
    line-height: 1.1;
    text-align: center;
    font-weight: bold;
}

.mmv-side-bar {
    width: 360px;
    height: 100%;
    padding: 15px;
    flex-shrink: 0;
    display: flex;
    flex-direction: column;
    align-items: center;
}

.mmv-car-wrap {
    width: 100%;
    height: calc(100vh - 84px - 200px);
    // height: 500px;
    overflow-y: scroll;
    padding-right: 10px;
}

.mmv-car-item {
    padding: 10px;
    text-align: left;
    border: 1px solid #ddd;
    border-radius: 4px;
    margin-top: 5px;
    display: flex;
    flex-direction: column;
    //align-items: center;
    cursor: pointer;

    //span {
    //    flex: 1;
    //    margin: 0 5px;
    //}
    &.active {
        background: #ecf5ff;
        color: #409eff;
        border-color: #409eff;
    }
}

.car-item-row {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.refreshCountdown-carInfo {
    position: absolute;
    // top: 8;
    left: 400px;
    z-index: 20;
    background: #fff;
    border-radius: 4px;
    box-sizing: border-box;
    padding: 5px 20px;
    white-space: nowrap;
}

::v-deep .el-divider {
    background-color: white !important;
    margin: 10px 0 !important;
}

::v-deep .el-dialog__body {
    padding: 0 20px 30px !important;
}

.el-dropdown-link {
    cursor: pointer;
    color: #333;
}

.el-icon-arrow-down {
    font-size: 12px;
}
</style>